﻿// FluentViewModel (http://fluentviewmodel.codeplex.com/)
//
// Copyright © 2010 Kialco Group 
//
// The contents of this file are subject to the Mozilla Public
// License Version 1.1 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of
// the License at http://www.mozilla.org/MPL/
// 
// Software distributed under the License is distributed on an 
// "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
// implied. See the License for the specific language governing
// rights and limitations under the License.

using System;
using System.Collections.Generic;
using Castle.DynamicProxy;

namespace FluentViewModel
{
    public sealed class ViewModelContainer : IViewModelContainer
    {
        private readonly ProxyGenerator generator;
        private readonly IDictionary<string, Func<IViewModel>> resolve;

        internal ViewModelContainer() 
        {
            generator = new ProxyGenerator(new DefaultProxyBuilder());
            resolve = new Dictionary<string, Func<IViewModel>>();
        }

        public void Register(IViewModelConfiguration configuration)
        {
            resolve[configuration.Name] = () =>
            {
                var viewModel = generator.CreateInterfaceProxyWithoutTarget(configuration.ViewModelType, new ProxyGenerationOptions { BaseTypeForInterfaceProxy = typeof(ViewModel) }, new ViewModelInterceptor()) as IViewModel;
                if (viewModel == null) 
                    throw new InvalidOperationException("Unable to create view model instance.");
                viewModel.Initialize(configuration);
                return viewModel;
            };
            if (configuration.Transient) 
                return;
            IViewModel singletonViewModel = null;
            var resolver = resolve[configuration.Name];
            resolve[configuration.Name] = () => singletonViewModel ?? (singletonViewModel = resolver());
        }

        public object Resolve(Type type)
        {
            return resolve[type.FullName]();
        }

        public TViewModel Resolve<TViewModel>()
        {
            return (TViewModel)Resolve(typeof(TViewModel));
        }
    }
}